package com.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class JDBCTest {
    private static String DRIVER;
    private static String URL;
    private static String USERNAME;
    private static String PASSWORD;
    private static Connection connection=null;
    private static PreparedStatement ps=null;
    private static ResultSet rs=null;
    //加载包
    static {
        try {
            Properties properties = new Properties();
            InputStream is = JDBCTest.class.getClassLoader().
                    getResourceAsStream("mysql.properties");
            properties.load(is);
            DRIVER = properties.getProperty("driver");
            URL = properties.getProperty("url");
            USERNAME = properties.getProperty("username");
            PASSWORD = properties.getProperty("password");
            Class.forName(DRIVER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //创建连接
    public static Connection getConnection() throws Exception {
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        return connection;
    }
    //查询表中所有数据
    public static ResultSet selectAll(String sql)throws Exception{
        PreparedStatement ps = getConnection().prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        return rs;
    }
    //查询有条件的表中数据
    public static ResultSet select(String sql,String...str)throws Exception{
        PreparedStatement ps = getConnection().prepareStatement(sql);
        for (int i = 0; i < str.length; i++) {
            ps.setString(i+1,str[i]);
        }
        ResultSet rs = ps.executeQuery();
        return rs;
    }
    //关闭
    public static void closeAll()throws Exception{
        rs.close();
        ps.close();
        connection.close();
    }
}
